import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    TextInput,
    Platform,
    Image,
    Dimensions
} from 'react-native';
import Slider from '@react-native-community/slider'

import PropTypes from 'prop-types';
import MultiSlider from '../../dependencies/react-native-multi-slider/Slider.js';
import Label from '../label/index';
import Color from '../../config/theme/standard/color.js';
import Font from '../../config/theme/standard/fonts.js';
export default class Range extends Component {

    constructor(props) {
        super(props)
        //input的值是string，slider的值是number
        this.state = {
            defaultValue:this.props.defaultValue < this.props.minValue ? this.props.minValue :
                (this.props.defaultValue > this.props.maxValue ? this.props.maxValue : this.props.defaultValue),
            step: this.props.step,
            inputValue: '',
            multiSliderValue: props.multiSliderValue,
            isWideScreen: false // 鸿蒙适配是否宽屏
        }
    }

    componentWillUnmount() {
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
    }
    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }

    multiSliderValuesChange = values => {
        this.setState({
            multiSliderValue: values,
        });
    };

    //拖动滑块的过程中不断调用此回调
    valueChangeEvent=(value)=>{
        this.setState({
            defaultValue:value,
            inputValue:value+''
        })
        if(this.props.valueChangeEvent){
            this.props.valueChangeEvent(value)
        }
    }
    //结束滑动的时候调用此回调
    slidingCompleteEvent=(value)=>{
        this.setState({
            inputValue:this._formatInput(value+'')
        })
        if(this.props.slidingCompleteEvent){
            this.props.slidingCompleteEvent(value)
        }
    }
    //当文本框内容变化时调用此回调函数
    onChangeTextEvent=(value)=>{
        let defaultValue=0;
        let inputValue='';
        if(value==''){
            defaultValue=0;
            inputValue='';
        }else if(isNaN(Number(value.charAt(0)))){
            defaultValue=0;
            inputValue='';
        }else{
            defaultValue=parseInt(value);
            inputValue=value;
        }

        this.setState({
            defaultValue,
            inputValue
        })
    }
    //当文本框失去焦点的时候调用此回调函数
    onBlurEvent=()=>{
        let inputVal=this.state.inputValue;
        let newInputStr=this._formatInput(inputVal+'');
        this.setState({
            inputValue:newInputStr
        });
        if(this.props.blurEvent){
            this.props.blurEvent(inputVal)
        };
    }

    //money需要格式化的钱数
    _formatInput=(money,decimalDigits)=>{
        if (money == '') {
            return money;
        }
        //小数点后位数
        let num;
        num = decimalDigits ? decimalDigits : 2;
        num = num > 0 && num <= 20 ? num : 2;
        money = parseFloat(money.replace(/[^\d\.-]/g, '')).toFixed(num);
        //小数点左边
        let left = money.split('.')[0].split('').reverse();
        //小数点右边
        let right = money.split('.')[1];
        let newMoney = '';
        for (let i = 0; i < left.length; i++) {
            newMoney += left[i] + (( i + 1) % 3 == 0 && ( i + 1) != left.length ? ',' : '');
        }
        newMoney = newMoney.split('').reverse().join('') + '.' + right;
        return newMoney;
    }
    //对外提供的方法  改变step
    changedStep=(stepVal)=>{
        this.setState({step:stepVal})
    }
    //对外提供的方法  重置初始值
    resetVal=(val)=>{
        this.setState({
            defaultValue:val,
            inputValue:this._formatInput(val+'')
        })
    }
    //对外提供的方法  textInput获取焦点
    setInputFocus=()=>{
        this.refs.textInput.focus();
    }

    componentDidMount(){
        let inputVal=this.props.defaultValue;
        let newInputStr=this._formatInput(inputVal+'');
        this.setState({
            inputValue:newInputStr
        });
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)

    }

    onValuesChangeFinishEvent=(value)=>{
        if(this.props.onValuesChangeFinish){
            this.props.onValuesChangeFinish(value)
        }
    }

    render() {
        let { defaultValue, step, inputValue } = this.state;
        let { width, disabled, maxValue, minValue, maxText, minText, currencySymbol, currencyUnit, maximumTrackTintColor, processHeight, minimumTrackTintColor, maxLength, rangeType, multiSliderValue, trackStyle, selectedStyle, markerStyle, customMarkerLeft, customMarkerRight, leftImage, showCurrencySymbol } = this.props;
        const sliderWidth = this.props.sliderWidth || Dimensions.get('window').width * 0.9
        let rangeComponent = null;
        let SliderComponent = null;
        customMarkerLeft = () => {
            return (
                <View style={{width:20,height:20,borderRadius:30,borderWidth:1,borderColor:'#fa5050',backgroundColor:'white'}}>
                </View>
            )
        }
    
        customMarkerRight=()=>{
            return (
                <View style={{width:20,height:20,borderRadius:30,           borderWidth:1,borderColor:'#fa5050',backgroundColor:'white'}}>
                </View>
            )
        }
        let img = require('../../assets/icon_range_edit.png');
        if(Platform.OS =='ios'){
            SliderComponent=(
                <Slider style={styles.sliderStyle}
                    value={defaultValue}
                    onValueChange={this.valueChangeEvent}
                    onSlidingComplete={this.slidingCompleteEvent}
                    maximumValue={maxValue}
                    minimumValue={minValue}
                    disabled={disabled}
                    maximumTrackTintColor={maximumTrackTintColor}
                    minimumTrackTintColor={minimumTrackTintColor}
                    processHeight={processHeight}
                    step={step}
                />
            );
        }else{
            SliderComponent=(
                <Slider style={styles.sliderStyle}
                    value={defaultValue}
                    onValueChange={this.valueChangeEvent}
                    onSlidingComplete={this.slidingCompleteEvent}
                    maximumValue={maxValue}
                    minimumValue={minValue}
                    disabled={disabled}
                    maximumTrackTintColor={maximumTrackTintColor}
                    minimumTrackTintColor={minimumTrackTintColor}
                    processHeight={processHeight}
                    thumbTintColor={'#ffbdbe'}
                    step={step}
                />
            );
        };
        if(rangeType=='1'){
            rangeComponent=(
                <View style={{width:'100%',alignItems:'center'}}>
                     <View style={styles.inputWrapper}>
                        {showCurrencySymbol ? 
                            <Label labelStyle={[{fontSize:20,       color:'#4b94ca',fontWeight:'bold'}]} type=          {'form'}  color={'navbar'}  text=                   {currencySymbol} /> :
                            <Image
                            style={styles.leftImageStyle}
                            source={img}
                        />}
                        <TextInput
                            ref="textInput"
                            style={styles.textInputStyle}
                            underlineColorAndroid='transparent'
                            onChangeText={(value)=>{this.onChangeTextEvent(value)}}
                            onBlur={()=>this.onBlurEvent()}
                            value={inputValue}
                            maxLength={maxLength}
                            keyboardType={(Platform.OS === 'web')? "phone-pad" :"numeric"}
                        />
                         <Label labelStyle={[{fontSize:Font.range.currencyUnitFontSize,color:Color.range.currencyUnit,fontWeight:'400'}]} text={currencyUnit} />
                     </View>
                    <View style={[styles.sliderWrapper,{width:width}]}>
                        {SliderComponent}
                        <Label labelStyle={[styles.circle]} type={'form'} color={'navbar'}  text={''}/>
                    </View>
                    <View style={styles.textWrapper}>
                        <View style={styles.textStyle}>
                            <Label labelStyle={[styles.fontStyle]} text={currencySymbol+' '+minValue} />
                            <Label labelStyle={[styles.fontStyle]} text={minText+''} />
                        </View>
                        <View style={styles.textStyle}>
                            <Label labelStyle={[styles.fontStyle]} text={currencySymbol+' '+this._formatInput(maxValue+'',2)} />
                            <Label labelStyle={[styles.fontStyle]}  text={maxText+''} />
                        </View>
                    </View>
                </View>
            )
        }else if(rangeType=='2'){
            rangeComponent=(
                <View style={{width:'100%',alignItems:'center'}}>
                    <View style={styles.textWrapper}>
                        <View style={styles.textStyle}>
                            <Label labelStyle={[styles.fontStyle]} type={'form'} color={'navbar'}  text={this.state.multiSliderValue[0]+''} />
                        </View>
                        <View style={styles.textStyle}>
                            <Label labelStyle={[styles.fontStyle]} type={'form'} color={'navbar'}  text={this.state.multiSliderValue[1]+''} />
                        </View>
                    </View>
                    <MultiSlider
                        values={[
                            this.state.multiSliderValue[0],
                            this.state.multiSliderValue[1],
                        ]}
                        sliderLength={sliderWidth}
                        onValuesChange={this.multiSliderValuesChange}
                        min={minValue}
                        max={maxValue}
                        allowOverlap={true}//是否允许两个滑块重叠
                        snapped={false}//滑动过程中，滑块和滑条是否紧紧吸附
                        onValuesChangeFinish={this.onValuesChangeFinishEvent}
                        trackStyle={trackStyle}
                        selectedStyle={selectedStyle}
                        markerStyle={markerStyle}
                        isMarkersSeparated={true}
                        step={step}
                        customMarkerLeft={customMarkerLeft}
                        customMarkerRight={customMarkerRight}
                    />
                </View>
            )
        }
        return (
            <View style={[styles.viewStyle,{width:width}]}>
               {rangeComponent}
            </View>
        );
    }
}

Range.propTypes = {
    //构件可展示的宽度
    width : PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.number
    ]),
    //是否禁用
    disabled : PropTypes.bool,
    //初始化时，出入框和滑块的默认值
    defaultValue : PropTypes.number,
    //滑块的最大值
    maxValue : PropTypes.number,
    //滑块的最小值
    minValue : PropTypes.number,
    //滑块的文本
    maxText:PropTypes.string,
    //滑块的文本
    minText:PropTypes.string,
    //滑块的移动的步长
    step : PropTypes.number,
    //货币符号
    currencySymbol:PropTypes.string,
    //货币单位
    currencyUnit:PropTypes.string,
    //输入框可输入的最大长度
    maxLength:PropTypes.number,
    //滑块右侧轨道的颜色
    maximumTrackTintColor:PropTypes.string,
    //滑块左侧轨道的颜色
    minimumTrackTintColor:PropTypes.string,
    //进度条高度
    processHeight:PropTypes.number,
    //结束滑动的时候调用此回调
    slidingCompleteEvent:PropTypes.func,
    //拖动滑块的过程中不断调用此回调
    valueChangeEvent:PropTypes.func,
    //输入框失去焦点时触发的事件
    blurEvent:PropTypes.func,
    
    //滑块类型
    rangeType:PropTypes.string,
    //两个端点的初始值
    multiSliderValue:PropTypes.array,
    //滑块拖动完成事件
    onValuesChangeFinish:PropTypes.func,
    //两个端点以外的样式
    trackStyle:PropTypes.object,
    //两个端点之间的样式
    selectedStyle:PropTypes.object,
    //两个端点的样式
    markerStyle:PropTypes.object,
    //滑块宽度
    sliderWidth:PropTypes.number,
    //左侧自定义手柄
    customMarkerLeft:PropTypes.func,
    //右侧自定义手柄
    customMarkerRight:PropTypes.func,
    //图片
    leftImage:PropTypes.any,
    //进度条高度
    processHeight:PropTypes.number,
    //是否显示货币符号
    showCurrencySymbol:PropTypes.bool
}

Range.defaultProps = {
    width : '80%',
    disabled : false,
    defaultValue : 0,
    maxValue : 100,
    minValue : 0,
    maxText:'最高',
    minText:'最低',
    maxLength:12,
    step : 1,
    showCurrencySymbol:true,
    currencySymbol:'¥',
    currencyUnit:'/RMB',
    maximumTrackTintColor:Color.range.selectBackground,
    minimumTrackTintColor:Color.range.selectBackground,
    processHeight:9,
    rangeType:'1',
    multiSliderValue:[1,10],
    trackStyle:{backgroundColor:'#d8d8d8'},
    selectedStyle:{backgroundColor:'#ff7b7b'},
    markerStyle:{backgroundColor:'#ff7b7b'},
    sliderWidth:280,
    processHeight:4
}

const styles = StyleSheet.create({
    viewStyle: {
        width:'80%',
        alignItems:'center',
        justifyContent:'center'
    },
    inputWrapper:{
        flexDirection:'row',
        alignItems:'center',
        justifyContent: 'center'
    },
    leftImageStyle:{
        height: 16,
        width: 16,
        alignSelf: 'center',
        justifyContent: 'center',
        resizeMode: 'contain'
    },
    textInputStyle:{
        height: 40,
        width:'40%',
        marginLeft:16,
        marginRight:16,
        borderColor: Color.range.inputBorder,
        borderBottomWidth:1,
        borderStyle:'solid',
        padding:0,
        margin:0,
        fontSize:Font.range.inputFontSize,
        color:Color.range.input,
        fontWeight:'400',
        textAlign:'center'
    },
    sliderWrapper:{
        flexDirection:'row',
        alignItems:'center',
        marginTop:10,
        //marginBottom:15
    },
    circle:{
        //width:10,
        //height:10,
        //backgroundColor:'green',
        //borderRadius:5,
        //borderColor:'green',
        //borderWidth:1,
        //position:'absolute',
        //left:0,
        //top:15

    },
    sliderStyle:{
        flex:1
    },
    textWrapper:{
        width:'100%',
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'space-between',
        height:50,
        marginTop:-5
    },
    textStyle:{
        flexDirection:'column',
        alignItems:'center',

    },
    fontStyle:{
        fontSize:Font.range.bottomFontSize,
        color:Color.range.bottom,
        fontWeight:'400'
    },
    text: {
        alignSelf: 'center',
        paddingVertical: 20,
    },
    sliderOne: {
        flexDirection: 'row',
        justifyContent: 'space-around',
    },


});
